package com.augrain.microframework.trace.common.traceid;


import com.augrain.microframework.core.util.IpUtils;
import com.augrain.microframework.core.util.StringUtils;
import com.augrain.microframework.core.util.SysUtils;
import com.augrain.microframework.core.util.time.DateTimeUtils;

/**
 * 默认生成traceId
 *
 * @author biaoy
 * @since 2021/08/21
 */
public class DefaultTraceGenerator implements TraceIdGenerator {

    private volatile static int SERIAL_NUM = 1000;

    @Override
    public String generateTraceId() {
        // 服务器IP（8） + 产生ID时候的时间（13位） + 自增序列（4位） + 当前进程号（5位）
        return IpUtils.ipToHex(IpUtils.getLocalIp()) +
                DateTimeUtils.getNowMillis() +
                getAutoIncrementSerialNum() +
                StringUtils.leftPad(SysUtils.getPid(), "0", 5);
    }

    public int getAutoIncrementSerialNum() {
        synchronized (DefaultTraceGenerator.class) {
            SERIAL_NUM++;
            if (SERIAL_NUM > 9999) {
                SERIAL_NUM = 1000;
            }
            return SERIAL_NUM;
        }
    }
}
